<template>
  <div class="resource-property-manager-v3">
    <div class="manager-header">
      <h2>资源属性管理 (FormCreate可视化版)</h2>
      <div class="header-actions">
        <Button type="primary" @click="saveSchema" :loading="saving">
          <IconifyIcon icon="ant-design:save-outlined" />
          保存结构
        </Button>
        <Button @click="previewForm">
          <IconifyIcon icon="ant-design:eye-outlined" />
          预览表单
        </Button>
      </div>
    </div>

    <Tabs v-model:active-key="activeTab" class="manager-tabs">
      <TabPane key="designer" tab="可视化设计">
        <div class="designer-container">
          <div class="designer-toolbar">
            <Button type="primary" @click="handleSave">
              <IconifyIcon icon="ant-design:save-outlined" />
              保存设计
            </Button>
            <Button @click="handleReset">
              <IconifyIcon icon="ant-design:reload-outlined" />
              重置设计
            </Button>
          </div>

          <div class="designer-content">
            <FcDesigner
              ref="designerRef"
              class="h-full min-h-[600px]"
              :config="designerConfig"
            />
          </div>
        </div>
      </TabPane>

      <TabPane key="preview" tab="表单预览">
        <div class="preview-container">
          <div class="preview-toolbar">
            <Button
              type="primary"
              @click="submitPreviewForm"
              :loading="submitting"
            >
              <IconifyIcon icon="ant-design:check-outlined" />
              提交表单
            </Button>
            <Button @click="resetPreviewForm">
              <IconifyIcon icon="ant-design:reload-outlined" />
              重置表单
            </Button>
          </div>

          <div class="preview-content">
            <div v-if="!hasFormRules" class="empty-state">
              <IconifyIcon icon="ant-design:form-outlined" class="empty-icon" />
              <p>暂无表单设计，请先在"可视化设计"中设计表单</p>
            </div>
            <FormCreate
              v-else
              ref="formCreateRef"
              :rule="formRules"
              :option="formOptions"
              :value="formData"
              @submit="onFormSubmit"
            />
          </div>

          <div v-if="Object.keys(formData).length > 0" class="preview-data">
            <h4>表单数据</h4>
            <pre>{{ JSON.stringify(formData, null, 2) }}</pre>
          </div>
        </div>
      </TabPane>
    </Tabs>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import { Tabs, TabPane, Button, message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import FcDesigner from '@form-create/antd-designer';
import FormCreate from '@form-create/ant-design-vue';

import { useFormCreateDesigner } from '#/components/form-create';
// Props
const props = defineProps<{
  resource: any;
}>();

// Emits
const emit = defineEmits<{
  update: [data: any];
}>();

// 响应式数据
const activeTab = ref('designer');
const saving = ref(false);
const submitting = ref(false);

// 设计器相关
const designerRef = ref<InstanceType<typeof FcDesigner>>();
const formCreateRef = ref<InstanceType<typeof FormCreate>>();

// 表单数据
const formRules = ref<any[]>([]);
const formOptions = ref({
  submitBtn: false,
  resetBtn: false,
  formData: {},
});
const formData = ref({});

// 设计器配置
const designerConfig = ref({
  switchType: [],
  autoActive: true,
  useTemplate: false,
  formOptions: {
    form: {
      labelWidth: '100px',
    },
  },
  fieldReadonly: false,
  hiddenDragMenu: false,
  hiddenDragBtn: false,
  hiddenMenu: [],
  hiddenItem: [],
  hiddenItemConfig: {},
  disabledItemConfig: {},
  showSaveBtn: false,
  showConfig: true,
  showBaseForm: true,
  showControl: true,
  showPropsForm: true,
  showEventForm: true,
  showValidateForm: true,
  showFormConfig: true,
  showInputData: true,
  showDevice: true,
  appendConfigData: [],
});

// 计算属性
const hasFormRules = computed(() => {
  return formRules.value && formRules.value.length > 0;
});

// 保存设计
const handleSave = () => {
  if (designerRef.value) {
    const rules = designerRef.value.getRule();
    const options = designerRef.value.getOption();

    formRules.value = rules;
    formOptions.value = options;

    message.success('设计已保存');
  }
};

// 重置设计
const handleReset = () => {
  if (designerRef.value) {
    designerRef.value.setRule([]);
    designerRef.value.setOption({
      submitBtn: false,
      resetBtn: false,
      formData: {},
    });

    formRules.value = [];
    formOptions.value = {
      submitBtn: false,
      resetBtn: false,
      formData: {},
    };
    formData.value = {};

    message.success('设计已重置');
  }
};

// 预览表单
const previewForm = () => {
  activeTab.value = 'preview';
};

// 提交预览表单
const submitPreviewForm = async () => {
  submitting.value = true;
  try {
    if (formCreateRef.value) {
      const valid = await formCreateRef.value.validate();
      if (valid) {
        message.success('表单提交成功！');
        console.log('表单数据:', formData.value);
      }
    }
  } catch (error) {
    message.error('表单验证失败');
  } finally {
    submitting.value = false;
  }
};

// 重置预览表单
const resetPreviewForm = () => {
  if (formCreateRef.value) {
    formCreateRef.value.resetFields();
    formData.value = {};
    message.success('表单已重置');
  }
};

// 表单提交回调
const onFormSubmit = (formData: any) => {
  console.log('表单提交:', formData);
  message.success('表单提交成功！');
};

// 保存Schema
const saveSchema = async () => {
  saving.value = true;
  try {
    const schema = {
      id: props.resource.id,
      type: 'formcreate',
      rules: formRules.value,
      options: formOptions.value,
    };

    const response = await fetch('/mock-api/resource-center/property-schema', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(schema),
    });

    if (response.ok) {
      message.success('属性结构保存成功');
      emit('update', schema);
    } else {
      throw new Error('保存失败');
    }
  } catch (error) {
    message.error('保存失败: ' + (error as Error).message);
  } finally {
    saving.value = false;
  }
};

useFormCreateDesigner(designerRef); // 表单设计器增强
// 初始化
onMounted(async () => {
  try {
    // 加载已保存的Schema
    const response = await fetch(
      `/mock-api/resource-center/property-schema?resourceId=${props.resource.id}`,
    );
    if (response.ok) {
      const result = await response.json();
      if (result.data && result.data.type === 'formcreate') {
        formRules.value = result.data.rules || [];
        formOptions.value = result.data.options || {
          submitBtn: false,
          resetBtn: false,
          formData: {},
        };

        // 设置设计器
        if (designerRef.value) {
          designerRef.value.setRule(formRules.value);
          designerRef.value.setOption(formOptions.value);
        }
      }
    }
  } catch (error) {
    console.error('初始化失败:', error);
  }
});
</script>

<style lang="less" scoped>
.resource-property-manager-v3 {
  .manager-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    h2 {
      margin: 0;
      color: #262626;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .manager-tabs {
    :deep(.ant-tabs-content) {
      padding: 16px 0;
    }
  }

  .designer-container {
    .designer-toolbar {
      margin-bottom: 16px;
      display: flex;
      gap: 8px;
    }

    .designer-content {
      border: 1px solid #f0f0f0;
      border-radius: 6px;
      overflow: hidden;
    }
  }

  .preview-container {
    .preview-toolbar {
      margin-bottom: 16px;
      display: flex;
      gap: 8px;
    }

    .preview-content {
      border: 1px solid #f0f0f0;
      border-radius: 6px;
      padding: 20px;
      background-color: #fafafa;
      margin-bottom: 20px;
    }

    .empty-state {
      text-align: center;
      padding: 40px 20px;
      color: #8c8c8c;

      .empty-icon {
        font-size: 48px;
        margin-bottom: 16px;
        color: #d9d9d9;
      }

      p {
        margin: 0;
        font-size: 14px;
      }
    }

    .preview-data {
      border-top: 1px solid #f0f0f0;
      padding-top: 20px;

      h4 {
        margin: 0 0 12px 0;
        color: #262626;
        font-size: 14px;
      }

      pre {
        background-color: #f5f5f5;
        padding: 12px;
        border-radius: 4px;
        font-size: 12px;
        color: #595959;
        margin: 0;
        overflow-x: auto;
        max-height: 200px;
        overflow-y: auto;
      }
    }
  }
}
</style>
